package com.hjq.fcloud.other

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity
import cn.bingoogolapple.photopicker.util.BGAPhotoHelper
import cn.bingoogolapple.photopicker.util.BGAPhotoPickerUtil
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout
import com.hjq.base.BaseActivity
import com.hjq.fcloud.R
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.bean.CommonFileBean
import com.hjq.fcloud.bean.FileItemBean
import com.hjq.fcloud.utils.CommonUploadUtils
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import java.io.File

/**
 * 公共图片选择处理
 */
class SelectedImageViewHelper {

    companion object {
        /**
         * 拍照的请求码
         */
        private const val RC_CHOOSE_TAKE_PHOTO = 1

        /**
         * 图片预览界面
         */
        fun jumpPreview(
            mActivity: Activity?, selectedImageView: BGASortableNinePhotoLayout, position: Int
        ) {
            val photoPreviewIntentBuilder = BGAPhotoPreviewActivity.IntentBuilder(mActivity)
            photoPreviewIntentBuilder.previewPhotos(selectedImageView.getData())
                .currentPosition(position) // 当前预览图片的索引
            mActivity?.startActivity(photoPreviewIntentBuilder.build())
        }
    }

    //九宫格view
    private var mSelectedImageView: BGASortableNinePhotoLayout? = null

    private var mActivity: AppActivity? = null
    //上传成功的文件列表
    private var uploadSuccessList = ArrayList<CommonFileBean>()

    /**
     * RecycleView中存在BGASortableNinePhotoLayout复用问题，所以每次获取和添加都重新创建对象，要不然滑动会影响展示
     */
    fun getData():ArrayList<CommonFileBean>{
        var retList = ArrayList<CommonFileBean>()
        uploadSuccessList.forEach {
            retList.add(it)
        }
        return retList
    }

    /**
     * RecycleView中存在BGASortableNinePhotoLayout复用问题，所以每次获取和添加都重新创建对象，要不然滑动会影响展示
     */
    fun setData(data: ArrayList<FileItemBean>? = null){
        uploadSuccessList.clear()
        var realData = ArrayList<String>()
        data?.forEach {
            var commonFileBean = CommonFileBean()
            commonFileBean.url = it.url
            uploadSuccessList.add(commonFileBean)

            realData.add(it.url)
        }
        mSelectedImageView?.data  = realData
    }

    /**
     * 初始化图片选择控件
     */
    fun initSelectedImageView(
        activity: AppActivity, selectedImageView: BGASortableNinePhotoLayout, selectCount: Int = 1
    ) {
        this.mSelectedImageView = selectedImageView
        this.mActivity = activity

//        selectedImageView.setDeleteDrawableOverlapQuarter(true)
        selectedImageView.maxItemCount = selectCount
//        selectedImageView.setDeleteDrawableResId(R.mipmap.bga_pp_ic_delete)
        selectedImageView.setDeleteDrawableResId(R.drawable.photo_delete)
        selectedImageView.setPlusDrawableResId(R.drawable.img_camera)
        selectedImageView.setDelegate(object : BGASortableNinePhotoLayout.Delegate {
            override fun onClickAddNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                models: ArrayList<String>
            ) {
                var maxChooseCount =
                    mSelectedImageView!!.getMaxItemCount() - mSelectedImageView!!.getItemCount()
                choicePhotoWrapper(maxChooseCount)
            }

            override fun onClickDeleteNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                model: String,
                models: ArrayList<String>
            ) {
                uploadSuccessList.removeAt(position)
                selectedImageView.removeItem(position)
            }

            override fun onClickNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                model: String,
                models: ArrayList<String>
            ) {
                jumpPreview(mActivity, selectedImageView, position)
            }

            override fun onNinePhotoItemExchanged(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                fromPosition: Int,
                toPosition: Int,
                models: ArrayList<String>
            ) {
            }
        })
    }

    /**
     * 图片选择
     */
    fun choicePhotoWrapper(maxChooseCount: Int) {
        XXPermissions.with(mActivity)
            .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : PermissionCallback() {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    takePhoto()
                }

                private fun takePhoto() {
                    mSelectedImageView?.let { mSelectedImageView ->
                        try {
                            val cameraFileDir = File(mActivity?.cacheDir, "fcloud")
                            //获取拍照意图
                            var photoHelper = BGAPhotoHelper(cameraFileDir)
                            var intent = photoHelper.getTakePhotoIntent()
                            mActivity?.startActivityForResult(
                                intent,
                                object : BaseActivity.OnActivityCallback {
                                    override fun onActivityResult(resultCode: Int, data: Intent?) {
                                        val filePath = photoHelper?.getCameraFilePath()
                                        var fileExist = File(filePath).readBytes().size > 0
                                        if(!TextUtils.isEmpty(filePath) && fileExist){
                                            var files = ArrayList<String>()
                                            files.add(filePath)
                                            uploadFiles(files,{
                                                mSelectedImageView?.addLastItem(filePath)
                                            })
                                        }
                                    }
                                })
                        } catch (e: Exception) {
                            BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_take_photo)
                        }
                    }
                }
            })
    }

    fun uploadFiles(files: ArrayList<String>?, callBack: (ArrayList<String>) -> Unit) {
        mActivity?.let { mActivity ->
            mActivity.showDialog()
            var filesBean = getUploadFilesBean(files)
            CommonUploadUtils.uploadFiles(mActivity, filesBean, { success, errorMsg, urls ->
                mActivity.hideDialog()
                if (success) {
                    var retList = ArrayList<String>()
                    urls?.forEach {
                        uploadSuccessList.add(it)
                        retList.add(it.url)
                    }
                    callBack(retList)
                } else {
                    ToastUtils.show(errorMsg)
                }
            })
        }
    }

    private fun getUploadFilesBean(files: ArrayList<String>?): List<CommonFileBean> {
        var list = ArrayList<CommonFileBean>()
        files?.forEach {
            list.add(CommonFileBean(it))
        }
        return list
    }

}